package com.sangmo.fts.basic.service;

import com.sangmo.boot.framework.common.session.UserSession;
import com.sangmo.boot.framework.data.filter.NativeQueryBuilder;
import com.sangmo.boot.framework.data.filter.PageResult;
import com.sangmo.boot.framework.data.filter.PageSearch;
import com.sangmo.boot.framework.data.filter.ValueFilter;
import com.sangmo.boot.framework.plugin.dataview.crud.service.DelegateViewService;
import com.sangmo.boot.framework.plugin.dataview.crud.service.ViewService;
import com.sangmo.boot.framework.plugin.dataview.spi.jpa.NativeQueryBuilderFactory;
import com.sangmo.fts.basic.model.Notice;
import com.sangmo.fts.basic.service.NoticeEntityService;
import com.sangmo.fts.teacher.model.Examination;
import org.aspectj.weaver.ast.Not;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class NoticeService extends DelegateViewService<Notice> {

    @Autowired
    private NoticeEntityService noticeEntityService;

    @Override
    protected ViewService<Notice> getEntityService() {
        return noticeEntityService;
    }

    @Override
    public PageResult search(PageSearch ps) {
//        ps.getFilters().add(new ValueFilter("createdBy", ValueFilter.OP_EQ, UserSession.getUserInterface().getId()));
        return super.search(ps);
    }

    public PageResult<Notice> searchForStudent(PageSearch ps) {
        Long currentUserId = (Long) UserSession.getUserInterface().getId();
        NativeQueryBuilder builder = NativeQueryBuilderFactory.create()
                .selectForm("SELECT a.* FROM notice a ")
                .where(" EXISTS (SELECT uc.user_id from user_clazz uc where EXISTS(SELECT uc.clazz_id from user_clazz uc2 where uc2.user_id = :userId) and a.created_by = uc.user_id) ")
                .where(ps)
                .putVariable("userId", currentUserId)
                .transform(Notice.class);
        return builder.buildPage();
    }
}
